package com.jianying.day01;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink02_WC_Stream_bound
 * Package: com.atguigu.day01
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/3/29 13:53
 * @Version: 1.0
 */
public class Flink02_WC_Stream_Bound {
    public static void main(String[] args) throws Exception {
        // TODO 1 流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 指定以批的形式对数据进行处理
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
        // TODO 2 读取数据
        DataStreamSource<String> strDS = env.readTextFile("C:\\MyFiles\\Project\\bigdata_flink\\input\\word.txt");
        // TODO 3 对当前行数据扁平化处理 并类型转换 Tuple2(word, 1L)
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMapDS = strDS.flatMap(
                new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String lineStr, Collector<Tuple2<String, Long>> collector) throws Exception {
                        String[] words = lineStr.split(" ");
                        for (String word : words) {
                            collector.collect(Tuple2.of(word, 1L));
                        }
                    }
                }
        );
        // TODO 4 按单词分组
        KeyedStream<Tuple2<String, Long>, Tuple> keyByDS = flatMapDS.keyBy(0);
        // TODO 5 分组后聚合统计
        SingleOutputStreamOperator<Tuple2<String, Long>> sumDS = keyByDS.sum(1);
        // TODO 6 打印输出
        sumDS.print();
        // TODO 7 提交作业
        env.execute();
    }
}
